<template>
  <div class="table-box table-content">
    <ProTable
      ref="processProTable"
      :columns="columns"
      :request-api="getProcessList"
      :init-param="initParam"
      :request-auto="true"
      :data-callback="dataCallback"
      :search-col="{ xs: 1, sm: 1, md: 1, lg: 1, xl: 1 }"
      row-key="id"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" :icon="CirclePlus" @click="importProcess(scope)">导入流程</el-button>
      </template>
      <template #operation="scope">
        <el-button type="primary" :icon="Select" @click="toProcessInstance(scope)">流程实例</el-button>
        <el-button type="primary" :icon="Select" @click="checkProcessImg(scope)">查看流程图</el-button>
        <el-button type="primary" :icon="Select" @click="processSet(scope)">流程属性设置</el-button>
        <el-button type="primary" :icon="Select" @click="delProcess(scope)">删除</el-button>
      </template>
    </ProTable>
    <el-dialog v-model="importProcessBox" title="导入流程" width="30%">
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        name="processFile"
        :headers="token"
        :on-exceed="handleExceed"
        :action="processFile"
        :auto-upload="false"
        :limit="1"
        :on-change="chooseFile"
        :on-success="uploadSuccess"
        :on-error="uploadError"
      >
        <template #trigger>
          <el-button type="primary">选择文件</el-button>
        </template>
        <el-button class="ml-3" type="success" @click="submitUpload">部署流程</el-button>
        <template #tip>
          <div class="el-upload__tip">请选择jpdl或者zip文件！</div>
        </template>
      </el-upload>
    </el-dialog>
    <el-dialog v-model="dialogVisible" title="流程图" width="80%">
      <div>
        <img :src="processImgApi" alt="" />
      </div>
    </el-dialog>
    <el-dialog v-model="setProcessVisibel" title="流程图属性设置" width="80%" height="80%" @closed="closeClick">
      <div class="processBox">
        <div class="taskText">
          <div>流程类型：{{ processType }}</div>
          <div>流程节点</div>
          <p class="text" style="font-weight: bold; text-align: center; background-color: #e5e5e5">
            <span class="node">节点名称</span>
            <span class="node">节点出口</span>
          </p>
          <p
            class="text"
            v-for="(item, index) in taskAttribute"
            :key="item.id"
            @click="setTaskAttributeProcess(index, item.id)"
            :style="{ backgroundColor: selectedTaskIndex === index ? '#d3d3d3' : 'transparent' }"
          >
            <span class="node">{{ index + 1 + "," + item.activityName }}</span>
            <span class="node">
              <span v-for="e in item.flowTransitionDto" :key="e.id">{{ e.transitionName }} <br /></span>
            </span>
          </p>
        </div>
        <div class="taskAttribute">
          <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
            <el-tab-pane label="节点属性" name="first">
              <p v-if="selectActive === false">请先选择节点</p>
              <el-form label-position="right" label-width="auto" v-if="selectActive === true">
                <el-form-item label="选择指派方式" style="margin-bottom: 5px">
                  <el-select v-model="formData.assignTypeVal" placeholder="请选择" @change="getAssigneeType">
                    <el-option v-for="item in assignType" :key="item.value" :label="item.label" :value="item.value"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="指派组" style="margin-bottom: 5px" v-if="groupShow === true">
                  <el-input v-model="formData.orgNameObj.name" @click="showCascader = true"></el-input>
                  <el-cascader
                    v-model="selectedOrgValue"
                    :options="orgList"
                    :show-all-levels="false"
                    placeholder="所属技术组"
                    :props="props2"
                    @change="getOrg"
                    @visible-change="closeCas"
                    v-if="showCascader === true"
                  />
                </el-form-item>
                <el-form-item label="指派任务处理人" style="margin-bottom: 5px" v-if="assigneeNameShow === true">
                  <el-input
                    placeholder="请选择"
                    @click="dialog_flowProperty_assigneeName = true"
                    v-model="formData.assignee.name"
                    clearable
                  ></el-input>
                </el-form-item>
                <!-- 变量指派 -->
                <el-form-item label="指派组" style="margin-bottom: 5px" v-if="variablesAssigneeGroupShow === true">
                  <el-input
                    v-model="formData.variablesAssigneeGroupObj.name"
                    @click="variablesAssigneeGroupShow = true"
                  ></el-input>
                  <el-cascader
                    v-model="selectedVariablesOrgValue"
                    :options="orgList"
                    :show-all-levels="false"
                    placeholder="所属技术组"
                    :props="props2"
                    @change="getOrg2"
                    @visible-change="closeCas2"
                    v-if="showCascader === true"
                  />
                </el-form-item>
                <el-form-item label="指派任务处理人" style="margin-bottom: 5px" v-if="variablesAssigneeShow === true">
                  <el-select v-model="formData.variablesAssigneeVal" placeholder="请选择">
                    <el-option
                      v-for="item in variablesAssigneeType"
                      :key="item.value"
                      :label="item.name"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-dialog title="选择任务处理人" v-model="dialog_flowProperty_assigneeName">
                  <div :style="{ height: '500px' }">
                    <UserSelect @send-data="flowProperty_assigneeName" />
                  </div>
                </el-dialog>
                <el-form-item label="允许修改默认指派技术员" style="margin-bottom: 5px">
                  <el-switch v-model="formData.value1" />
                </el-form-item>
                <el-form-item label="允许修改默认指派组" style="margin-bottom: 5px">
                  <el-switch v-model="formData.value2" />
                </el-form-item>
                <el-form-item label="允许动态指派覆盖已有指派" style="margin-bottom: 5px">
                  <el-switch v-model="formData.value3" />
                </el-form-item>
                <el-form-item label="候选人" style="margin-bottom: 5px">
                  <el-input
                    placeholder="请选择"
                    @click="dialogRuleRequestNoTableVisible_action = true"
                    v-model="formData.approval.name"
                    clearable
                  ></el-input>
                </el-form-item>
                <el-dialog title="选择用户" v-model="dialogRuleRequestNoTableVisible_action">
                  <div :style="{ height: '500px' }">
                    <UserSelect @send-data="sendRuleRequestNoData_action" />
                  </div>
                </el-dialog>
                <el-form-item label="候选组" style="margin-bottom: 5px">
                  <el-input
                    placeholder="请选择"
                    @click="dialogGroup = true"
                    v-model="formData.candidateGroups.name"
                    clearable
                  ></el-input>
                  <el-dialog title="选择技术组" v-model="dialogGroup" style="width: 320px">
                    <div>
                      <TreeFilter
                        label="data"
                        id="attr"
                        title="部门列表"
                        :multiple="true"
                        :data="treeFilterData"
                        :default-value="treeInitParam.departmentId"
                        @change="changeTreeFilter"
                      />
                      <el-button @click="chooseCandidateGroups" type="primary" style="width: 100%; margin-top: 10px">
                        确认选择
                      </el-button>
                    </div>
                  </el-dialog>
                </el-form-item>
                <el-form-item label="状态" style="margin-bottom: 5px">
                  <el-select v-model="formData.requestStatusVal" placeholder="请选择">
                    <el-option
                      v-for="item in requestStatus"
                      :key="item.dcode"
                      :label="item.dname"
                      :value="item.dcode"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="流程跳转到此节点的验证条件" style="margin-bottom: 5px">
                  <el-select v-model="formData.flowProperty_validMethod_val" placeholder="请选择">
                    <el-option
                      v-for="item in flowProperty_validMethod"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="处理备注必填" style="margin-bottom: 5px">
                  <el-switch v-model="formData.value4" />
                </el-form-item>
                <el-form-item label="邮件处理流程" style="margin-bottom: 5px">
                  <el-switch v-model="formData.value5" />
                </el-form-item>
                <el-form-item label="回退给上次任务指派的技术员" style="margin-bottom: 5px">
                  <el-switch v-model="formData.value6" />
                </el-form-item>
                <el-form-item label="审批任务" style="margin-bottom: 5px" v-if="approverTaskShow === true">
                  <el-switch v-model="formData.value7" />
                </el-form-item>
                <el-form-item label="流程动作" style="margin-bottom: 5px">
                  <el-checkbox-group v-model="formData.checkList">
                    <el-checkbox label="请求回访" value="requestVisit" />
                    <el-checkbox label="申请升级" value="requestUpgradeApply" />
                    <el-checkbox label="升级请求" value="requestUpgrade" />
                    <el-checkbox label="审批加签" value="requestApporUser" />
                  </el-checkbox-group>
                </el-form-item>
                <el-form-item label="任务指派通知" style="margin-bottom: 5px">
                  <el-checkbox label="通知该请求的当前处理人" v-model="formData.taskAssigneeUserNotice" />
                  <el-checkbox label="通知指派组所有人员" v-model="formData.taskAssigneeGroupNotice" />
                </el-form-item>
                <el-form-item label="通知模板" style="margin-bottom: 5px">
                  <!-- <el-input v-model="flowProperty_noticeRule"  clearable></el-input> -->
                  <el-button @click="chooseNoticeRule" type="primary">选择</el-button>
                  <el-tag
                    v-for="tag in formData.noticeRuleTags"
                    :key="tag.id"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(tag)"
                    style="margin-left: 3px"
                  >
                    {{ tag.name }}
                  </el-tag>
                </el-form-item>
                <el-dialog title="选择模板" v-model="noticeRule">
                  <ProTable
                    ref="noticeProTable"
                    :columns="noticeColumns"
                    :request-api="getNoticeRuleList"
                    :init-param="noticeRuleInitParam"
                    :request-auto="true"
                    :data-callback="dataCallback"
                    :search-col="{ xs: 1, sm: 1, md: 1, lg: 1, xl: 1 }"
                  >
                    <template #operation="scope">
                      <el-button type="primary" :icon="Select" @click="selectNoticeRule(scope)">选择</el-button>
                    </template>
                  </ProTable>
                </el-dialog>
                <el-form-item label="匹配规则" style="margin-bottom: 5px">
                  <!-- <el-button @click="chooseRulePackage" type="primary">选择</el-button> -->
                  <el-input v-model="formData.flowProperty_rulePackage.name" clearable @click="chooseRulePackage"></el-input>
                </el-form-item>
                <el-dialog title="选择规则" v-model="rulePackage">
                  <ProTable
                    ref="rulePackageProTable"
                    :columns="rulePackageColumns"
                    :request-api="getRulePackageList"
                    :init-param="rulePackageInitParam"
                    :request-auto="true"
                    :data-callback="dataCallback"
                    :search-col="{ xs: 1, sm: 1, md: 1, lg: 1, xl: 1 }"
                  >
                    <template #operation="scope">
                      <el-button type="primary" :icon="Select" @click="selectRulePackage(scope)">选择</el-button>
                    </template>
                  </ProTable>
                </el-dialog>
                <el-form-item label="操作" style="margin-bottom: 5px">
                  <el-button @click="submitProcess" type="primary" v-loading.fullscreen.lock="fullscreenLoading">提交</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="流程图" name="second">
              <img :src="processImgApi" alt="" />
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup name="processManagement">
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import ProTable from "@/components/ProTable/index.vue";
import { CirclePlus, Select, EditPen } from "@element-plus/icons-vue";
import {
  getProcessList,
  getFlowProperty,
  getStatus,
  getNoticeRuleList,
  getRulePackageList,
  getAttribute,
  saveFlowActive,
  deleteProblemClass
} from "@/api/modules/processManagement";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { TabsPaneContext, ElMessage, ElMessageBox, ElLoading, genFileId } from "element-plus";
import type { UploadInstance, UploadProps, UploadRawFile } from "element-plus";
import UserSelect from "@/views/tools/userselect/index.vue";
import { getUserDepartment } from "@/api/modules/jggl";
import TreeFilter from "@/components/TreeFilter/treeFilter.vue";
import { useUserStore } from "@/stores/modules/user";
import type { CascaderValue } from "element-plus";
const router = useRouter();
onMounted(() => {
  getVal();
  // getRequestStatus();
  getTreeFilter();
  token.Authorization = useUserStore().token;
});
const processProTable = ref<ProTableInstance>();
const noticeProTable = ref<ProTableInstance>();
const rulePackageProTable = ref<ProTableInstance>();
//部署流程
const token = reactive({ Authorization: "" });
const importProcessBox = ref(false);
const importProcess = e => {
  importProcessBox.value = true;
};
const processFile = ref("api/pages/jbpm!deployProcessDefinitionXmlFile.action");
const chooseFile = e => {
  if (e.name.includes("zip")) {
    processFile.value = "api/pages/jbpm!deployProcessDefinitionFile.action";
  }
  if (e.name.includes("jpdl")) {
    processFile.value = "api/pages/jbpm!deployProcessDefinitionXmlFile.action";
  }
};
const uploadSuccess = e => {
  importProcessBox.value = false;
  processProTable.value?.getTableList();
};
const uploadError = e => {
  if (e.toString().includes("UploadAjaxError")) {
    ElMessage.error("请上传正确文件");
  }
};
const handleExceed: UploadProps["onExceed"] = files => {
  uploadRef.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  uploadRef.value!.handleStart(file);
};
const uploadRef = ref<UploadInstance>();
const submitUpload = e => {
  uploadRef.value!.submit();
};
//部署流程结束
// 删除流程
const delProcess = async scope => {
  const params = {
    deploymentId: scope.row.deploymentId
  };
  ElMessageBox.confirm("确实要删除选择的数据吗？", "删除确认", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    center: true
  })
    .then(async () => {
      try {
        const res = await deleteProblemClass(params);
        if ((res as any) === null) {
          ElMessage.success("删除成功");
          console.log(processProTable.value);
          processProTable.value?.getTableList();
        }
      } catch {
        ElMessage.error("此数据存在相关联的数据，不能删除");
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除"
      });
    });
};
const selectActive = ref(false);
const formData = reactive({
  assignTypeVal: "", //指派方式
  orgName: [] as CascaderValue[], //指派组
  orgNameObj: { name: "", id: "" }, //指派组对象
  assignee: { name: "", userId: "" }, //指派任务处理人
  variablesAssigneeVal: "", //指派任务处理人-变量指派
  variablesAssigneeGroup: [] as CascaderValue[], //指派组-变量指派
  variablesAssigneeGroupObj: { name: "", id: "" }, //指派组-变量指派对象
  value1: false, //允许修改默认指派技术员
  value2: false, //允许修改默认指派组
  value3: false, //允许动态指派覆盖已有指派
  approval: { name: "", userId: "" }, //候选人
  candidateGroups: { name: "", id: "" }, //候选组
  requestStatusVal: "", //状态
  flowProperty_validMethod_val: "", //流程跳转到此节点的验证条件
  value4: false, //处理备注必填
  value5: false, //邮件处理流程
  value6: false, //回退给上次任务指派的技术员
  value7: false, //审批任务
  checkList: [], //流程动作
  taskAssigneeUserNotice: false, //任务指派通知
  taskAssigneeGroupNotice: false, //任务指派通知
  noticeRuleTags: [] as { name: string; id: number }[], //通知模板
  flowProperty_rulePackage: { name: "", id: 0 } //匹配规则
});
const dialogGroup = ref(false);
const treeInitParam = reactive({ departmentId: "1" });
const candidateGroups = reactive({
  name: "",
  id: ""
});
// 树形筛选切换
const changeTreeFilter = (val: any) => {
  if (val instanceof Array) {
    return;
  }
  console.log(val);
  let groupName = "";
  let groupNo = "";
  (val as any).forEach(item => {
    groupName += item.orgName + ",";
    groupNo += item.orgNo + ",";
  });
  formData.candidateGroups.name = groupName;
  formData.candidateGroups.id = groupNo.toString();
};
//确认选择候选组
const chooseCandidateGroups = () => {
  console.log(candidateGroups);
  dialogGroup.value = false;
};
//部门列表
const treeFilterData = ref<any>([]);
const getTreeFilter = async () => {
  const data = await getUserDepartment();
  if (data) {
    treeFilterData.value = data;
    treeInitParam.departmentId = treeFilterData.value[0].attr.orgNo;
  }
};
const selectedTaskIndex = ref<number | null>(null); // 新增状态变量
//节点id
const taskId = ref<number>();
const setTaskAttributeProcess = async (index: number, id: number) => {
  selectedTaskIndex.value = index; // 设置被点击的索引
  selectActive.value = true;
  const params = {
    "flowActivityDTO.id": id
  };
  taskId.value = id;
  const res = await getAttribute(params);
  if (res as any) {
    formData.noticeRuleTags = [];
    const result = res as any;
    if (result.assignType === "dynamicAssignee") {
      groupShow.value = true;
      assigneeNameShow.value = true;
      variablesAssigneeShow.value = false;
      variablesAssigneeGroupShow.value = false;
    } else if (result.assignType === "variablesAssignee") {
      groupShow.value = false;
      variablesAssigneeShow.value = true;
      variablesAssigneeGroupShow.value = true;
      assigneeNameShow.value = false;
    } else {
      groupShow.value = false;
      variablesAssigneeShow.value = false;
      variablesAssigneeGroupShow.value = false;
      assigneeNameShow.value = false;
    }
    formData.orgNameObj.name = result.groupName;
    formData.orgNameObj.id = result.groupNo;
    formData.assignee.name = result.assigneeName;
    formData.assignee.userId = result.assigneeNo;
    formData.assignTypeVal = result.assignType;
    formData.value1 = result.allowUdateDefaultAssignee;
    formData.value2 = result.allowUdateDefaultAssigneeGroup;
    formData.value3 = result.isUpdateEventAssign;
    formData.approval.name = result.candidateUsersName;
    formData.approval.userId = result.candidateUsersNo;
    formData.candidateGroups.name = result.candidateGroupsName;
    formData.candidateGroups.id = result.candidateGroupsNo;
    formData.requestStatusVal = result.statusNo;
    formData.flowProperty_validMethod_val = result.validMethod;
    formData.value4 = result.remarkRequired;
    formData.value5 = result.mailHandlingProcess;
    formData.value6 = result.isFallbackToTechnician;
    formData.value7 = result.approverTask;
    formData.checkList = result.taskActions;
    formData.taskAssigneeUserNotice = result.taskAssigneeUserNotice;
    formData.taskAssigneeGroupNotice = result.taskAssigneeGroupNotice;
    let noticeRule = result.noticeRule === "" ? [] : result.noticeRule.split(",");
    let noticeRuleId = result.noticeRuleIds === "" ? [] : result.noticeRuleIds.split(",");
    if (noticeRule.length !== 0) {
      noticeRule.forEach((item, index) => {
        formData.noticeRuleTags.push({
          name: item,
          id: noticeRuleId[index]
        });
      });
    }
    formData.flowProperty_rulePackage.name = result.matchRuleName;
  }
};
const groupShow = ref(false);
const assigneeNameShow = ref(false);
const variablesAssigneeGroupShow = ref(false);
const variablesAssigneeShow = ref(false);
const getAssigneeType = e => {
  if (e === "autoAssignee") {
    groupShow.value = false;
    assigneeNameShow.value = false;
    variablesAssigneeShow.value = false;
    variablesAssigneeGroupShow.value = false;
  } else if (e === "dynamicAssignee") {
    groupShow.value = true;
    assigneeNameShow.value = true;
    variablesAssigneeShow.value = false;
    variablesAssigneeGroupShow.value = false;
  } else if (e === "variablesAssignee") {
    groupShow.value = false;
    assigneeNameShow.value = false;
    variablesAssigneeShow.value = true;
    variablesAssigneeGroupShow.value = true;
  } else if (e === "ruleAssignee") {
    groupShow.value = false;
    assigneeNameShow.value = false;
    variablesAssigneeShow.value = false;
    variablesAssigneeGroupShow.value = false;
  } else {
    groupShow.value = false;
    assigneeNameShow.value = false;
    variablesAssigneeShow.value = false;
    variablesAssigneeGroupShow.value = false;
    return;
  }
};
const columns = ref<ColumnProps<any>[]>([
  {
    type: "selection"
  },
  {
    label: "ID",
    prop: "id"
    // width: 240
  },
  {
    label: "名称",
    prop: "name"
    // width: 240
  },
  {
    label: "键",
    prop: "key"
    // width: 240
  },
  {
    label: "版本",
    prop: "version"
    // width: 100
  },
  { prop: "operation", label: "操作", width: 650 }
]);
const getNoticeRuleDescription = noticeRuleType => {
  const noticeRuleMap = {
    requester: "请求人或报告人",
    technician: "指派的技术员",
    technicalGroup: "指派的技术组",
    owner: "负责人",
    taskGroupAndTechnician: "任务指派对象(组或技术员)",
    taskTechnicalGroupLeader: "指派组组长"
  };

  if (noticeRuleType.includes(";")) {
    // 处理多种类型的情况
    return noticeRuleType
      .split(";")
      .map(type => noticeRuleMap[type] || "") // 映射每个类型
      .filter(Boolean) // 去掉空值
      .join(";"); // 用分号拼接
  }
  // 返回单个类型的映射结果，或默认值
  return noticeRuleMap[noticeRuleType] || "";
};
const getNoticeType = (typeList: any) => {
  const noticeTypeMap = {
    imNotice: "IM消息通知",
    mailNotice: "邮箱通知",
    pushNotice: "手机消息推送",
    smsNotice: "短信通知"
  };
  let noticeTypeStr = "";
  Object.keys(typeList).forEach(key => {
    if (typeList[key] === "true") {
      noticeTypeStr += noticeTypeMap[key] + ";";
    }
  });
  return noticeTypeStr;
};
const noticeColumns = ref<ColumnProps[]>([
  { label: "ID", prop: "noticeRuleId" },
  { label: "通知模板名称", prop: "noticeRuleName" },
  {
    label: "通知对象",
    prop: "noticeRuleType",
    render(h) {
      if (h.row.noticeRuleType !== "") {
        return getNoticeRuleDescription(h.row.noticeRuleType);
      }
      return " ";
    }
  },
  {
    label: "通知方式",
    prop: "mailNotice",
    render(h) {
      if (h.row) {
        const noticeType = {
          imNotice: h.row.imNotice.toString(),
          mailNotice: h.row.mailNotice.toString(),
          pushNotice: h.row.pushNotice.toString(),
          smsNotice: h.row.smsNotice.toString()
        };
        return getNoticeType(noticeType);
      }
      return "";
    }
  },
  {
    label: "状态",
    prop: "useStatus",
    render(h) {
      switch (h.row.useStatus.toString()) {
        case "true":
          return "启用";
        case "false":
          return "禁用";
        default:
          return "";
      }
    }
  },
  { prop: "operation", label: "操作" }
]);
const rulePackageColumns = ref<ColumnProps[]>([
  { label: "ID", prop: "rulePackageNo" },
  {
    label: "规则包名称",
    prop: "packageName",
    render(h) {
      if (h.row.packageName) {
        let packageName = h.row.packageName.split(".");
        return packageName[packageName.length - 1];
      } else {
        return "";
      }
    }
  },
  { label: "别名", prop: "rulePackageRemarks" },
  { prop: "operation", label: "操作" }
]);
const initParam = ref("");
const noticeRuleInitParam = ref({
  pageNum: 1,
  pageSize: 10
});
const rulePackageInitParam = ref({
  pageNum: 1,
  pageSize: 10
});
const dialogVisible = ref(false);
const setProcessVisibel = ref(false);
const dataCallback = (data: any) => {
  return {
    list: data.data,
    total: data.totalSize,
    pageNum: data.page,
    pageSize: data.rows
  };
};
const activeName = ref("first");

const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event);
};
const closeClick = () => {
  selectedTaskIndex.value = null;
  selectActive.value = false;
};

const toProcessInstance = scope => {
  router.replace("/workflow/processManagement/processInstance_process?processId=" + scope.row.id);
};
const processImgApi = ref("");
const checkProcessImg = async scope => {
  dialogVisible.value = true;
  processImgApi.value = "api/jbpm!getProcessImage.action?processDefinitionId=" + scope.row.id;
};
const taskAttribute = ref<any[]>([]);
const processType = ref("");
const processSet = async scope => {
  taskAttribute.value = [];
  setProcessVisibel.value = true;
  processImgApi.value = "api/jbpm!getProcessImage.action?processDefinitionId=" + scope.row.id;
  const params = {
    processDefinitionId: scope.row.id
  };
  const data = await getFlowProperty(params);
  (data as any).flowActivityDTO.forEach(item => {
    if (item.activityType === "task") {
      taskAttribute.value.push(item);
    }
  });
  if (scope.row.key.includes("request")) {
    processType.value = "请求";
    getRequestStatus({ "dataDictionaryQueryDto.groupCode": "requestStatus" });
    flowProperty_validMethod.value = [
      { label: "解决方案不允许为空", value: "SolutionsNotEmptyValidate" },
      { label: "分类、影响范围、紧急度不允许为空", value: "RequestRequiredVerification" }
    ];
  } else if (scope.row.key.includes("problem")) {
    processType.value = "问题";
    getRequestStatus({ "dataDictionaryQueryDto.groupCode": "problemStatus" });
    flowProperty_validMethod.value = [{ label: "解决方案不能为空", value: "ProblemSolutionsNotEmptyValidate" }];
  } else if (scope.row.key.includes("release")) {
    processType.value = "发布";
    getRequestStatus({ "dataDictionaryQueryDto.groupCode": "releaseStatus" });
    flowProperty_validMethod.value = [{ label: "发布所关联的变更流程全部关闭", value: "ReleaseRelatedChangeAllCloseValidate" }];
  } else if (scope.row.key.includes("change")) {
    processType.value = "变更";
    getRequestStatus({ "dataDictionaryQueryDto.groupCode": "changeStatus" });
    approverTaskShow.value = true;
    flowProperty_validMethod.value = [
      { label: "变更审批成员不可以空!", value: "ChangeApproverNotNullValidate" },
      { label: "变更计划不能为空!", value: "ChangePlanNotNullValidate" },
      { label: "相关联请求要求全部处于关闭状态!", value: "RelatedRequestAllCloseStatus" },
      { label: "流程指派的技术员不能与变更指派的技术员一致!", value: "FlowAssignUnEqualChangeAssignValidate" }
    ];
  } else {
    processType.value = "";
  }
};
//流程图属性配置
const assignType = ref([
  { label: "顺延指派", value: "autoAssignee" },
  { label: "手动指派", value: "dynamicAssignee" },
  { label: "变量指派", value: "variablesAssignee" },
  { label: "规则指派", value: "ruleAssignee" }
]);
const approverTaskShow = ref(false);
const dialogRuleRequestNoTableVisible_action = ref(false);
const dialog_flowProperty_assigneeName = ref(false);
const sendRuleRequestNoData_action = (data: any) => {
  dialogRuleRequestNoTableVisible_action.value = false;
  if (formData.approval.name !== "" && formData.approval.userId !== "") {
    formData.approval.name = formData.approval.name + ";" + data.fullName;
    formData.approval.userId = formData.approval.userId + ";" + data.userId;
  } else {
    formData.approval.name = data.fullName;
    formData.approval.userId = data.userId;
  }
};
const flowProperty_assigneeName = (data: any) => {
  dialog_flowProperty_assigneeName.value = false;
  formData.assignee.name = data.fullName;
  formData.assignee.userId = data.userId;
};
const variablesAssigneeType = ref([
  { name: "请求人", value: "creator" },
  { name: "现指派技术员", value: "technician" },
  { name: "指派组的负责人", value: "groupHead" },
  { name: "请求人所属机构第一层负责人", value: "leader_0" },
  { name: "请求人所属机构第二层负责人", value: "leader_1" },
  { name: "请求人所属机构第三层负责人", value: "leader_2" },
  { name: "请求人所属机构第四层负责人", value: "leader_3" }
]);
const orgName = reactive({ name: "", id: 0 });
const getOrg = (e: CascaderValue) => {
  const values = Array.isArray(e) ? e : [e];
  if (values.length > 0) {
    const lastItem = values[values.length - 1] as any;
    formData.orgNameObj.name = lastItem.orgName;
    formData.orgNameObj.id = lastItem.orgNo;
  }
};
const getOrg2 = (e: CascaderValue) => {
  const values = Array.isArray(e) ? e : [e];
  if (values.length > 0) {
    const lastItem = values[values.length - 1] as any;
    formData.variablesAssigneeGroupObj.name = lastItem.orgName;
    formData.variablesAssigneeGroupObj.id = lastItem.orgNo;
  }
};
const closeCas = e => {
  console.log(e);
  if (e === false) {
    showCascader.value = false;
  }
};
const closeCas2 = e => {
  if (e === false) {
    showCascader.value = false;
  }
};
const orgList = ref<any>([]);
const orgList2 = ref<any>([]);
const props1 = {
  checkStrictly: true,
  multiple: true,
  label: "data",
  value: "attr"
};
const props2 = {
  checkStrictly: true,
  multiple: false,
  label: "data",
  value: "attr"
};
const showCascader = ref(false);
const getVal = async () => {
  orgList.value = [];
  orgList2.value = [];
  const list = await getUserDepartment();
  orgList.value = list[0].children;
  orgList2.value = list[0].children;
};
const requestStatus = ref<any>([]);
const getRequestStatus = async e => {
  const data = await getStatus(e);
  requestStatus.value = [];
  requestStatus.value = data;
};
const flowProperty_validMethod = ref<any>([]);
const flowProperty_noticeRule = ref("");
const noticeRule = ref(false);
const noticeRuleTags = ref<any>([]);
const handleClose = (tag: any) => {
  formData.noticeRuleTags.splice(formData.noticeRuleTags.indexOf(tag), 1);
};
const chooseNoticeRule = () => {
  noticeRule.value = true;
};
const selectNoticeRule = scope => {
  noticeRule.value = false;
  flowProperty_noticeRule.value = scope.row.noticeRuleName;
  if (formData.noticeRuleTags.length !== 0) {
    if (!formData.noticeRuleTags.some(item => item.name === scope.row.noticeRuleName)) {
      formData.noticeRuleTags.push({
        name: scope.row.noticeRuleName,
        id: scope.row.noticeRuleId
      });
    } else {
      ElMessageBox.alert("规则名称已存在!", "提示", {
        confirmButtonText: "OK"
      });
    }
  } else {
    formData.noticeRuleTags.push({
      name: scope.row.noticeRuleName,
      id: scope.row.noticeRuleId
    });
  }
};
const rulePackage = ref(false);
const chooseRulePackage = () => {
  rulePackage.value = true;
};
const selectRulePackage = scope => {
  let pName = scope.row.packageName.split(".");
  formData.flowProperty_rulePackage.name = pName[pName.length - 1];
  formData.flowProperty_rulePackage.id = scope.row.rulePackageNo;
  rulePackage.value = false;
};
const fullscreenLoading = ref(false);
const submitProcess = async () => {
  let noticeRuleIds = "";
  let noticeRuleId = "";
  let noticeRule = "";
  let taskActions = "";
  formData.noticeRuleTags.forEach(item => {
    if (item.id !== undefined) {
      noticeRuleIds += item.id + ",";
      noticeRuleId += "noticeRuleId=" + item.id + "&";
    }
    if (item.name !== "") {
      noticeRule += "flowActivityDTO.noticeRule=" + item.name + "&";
    }
  });
  formData.checkList.forEach(item => {
    if (item) {
      taskActions += "flowActivityDTO.taskActions=" + item + "&";
    }
  });
  noticeRuleIds = noticeRuleIds.slice(0, -1);
  noticeRuleId = noticeRuleId.slice(0, -1);
  noticeRule = noticeRule.slice(0, -1);
  taskActions = taskActions.slice(0, -1);
  const params = {
    "flowActivityDTO.id": taskId.value,
    "flowActivityDTO.dynamicAssignee": true,
    "flowActivityDTO.assignType": formData.assignTypeVal,
    "flowActivityDTO.groupNo": formData.orgNameObj.id,
    "flowActivityDTO.assigneeNo": formData.assignee.userId,
    "flowActivityDTO.variablesAssigneeGroupNo": formData.variablesAssigneeGroupObj.id,
    "flowActivityDTO.variablesAssigneeGroupName": formData.variablesAssigneeGroupObj.name,
    "flowActivityDTO.variablesAssigneeType": formData.variablesAssigneeVal,
    "flowActivityDTO.allowUdateDefaultAssignee": formData.value1,
    "flowActivityDTO.allowUdateDefaultAssigneeGroup": formData.value2,
    "flowActivityDTO.isUpdateEventAssign": formData.value3,
    "flowActivityDTO.candidateUsersNo": formData.approval.name,
    "flowActivityDTO.candidateUsersName": formData.approval.userId,
    "flowActivityDTO.candidateGroupsNo": formData.candidateGroups.id,
    "flowActivityDTO.candidateGroupsName": formData.candidateGroups.name,
    "flowActivityDTO.statusNo": formData.requestStatusVal,
    "flowActivityDTO.validMethod": formData.flowProperty_validMethod_val,
    "flowActivityDTO.remarkRequired": formData.value4,
    "flowActivityDTO.mailHandlingProcess": formData.value5,
    "flowActivityDTO.isFallbackToTechnician": formData.value6,
    "flowActivityDTO.taskAssigneeUserNotice": formData.taskAssigneeUserNotice,
    "flowActivityDTO.taskAssigneeGroupNotice": formData.taskAssigneeGroupNotice,
    "flowActivityDTO.noticeRuleIds": noticeRuleIds,
    "flowActivityDTO.matchRuleId": formData.flowProperty_rulePackage.id,
    "flowActivityDTO.matchRuleName": formData.flowProperty_rulePackage.name
  };
  const res = await saveFlowActive(noticeRuleId, noticeRule, taskActions, params);
  fullscreenLoading.value = true;
  if ((res as any) === null) {
    fullscreenLoading.value = false;
    ElMessage.success("提交完成");
  } else {
    fullscreenLoading.value = false;
    ElMessage.error("出错了，请联系管理人员");
  }
};
const selectedOrgValue = ref<CascaderValue>();
const selectedVariablesOrgValue = ref<CascaderValue>();
</script>
<style lang="scss" scoped>
.processBox {
  display: flex;
  width: 100%;
  height: 750px;
  padding: 10px;
  overflow: hidden;
  .taskText {
    width: 40%;
    margin-right: 10px;
    .text {
      width: 100%;
      margin: 0;
      border-bottom: 1px solid #e5e5e5;
      .node {
        display: inline-block;
        width: 50%;
        line-height: 25px;
        vertical-align: text-top;
      }
    }
  }
}
</style>
